// LibraryManagementGUI.java - 整合数据库功能的管理员界面
package com.library.gui;

import com.library.entity.*;
import com.library.service.LibraryDataService;
import com.library.dao.BookDAO;
import com.library.dao.ReaderDAO;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class LibraryManagementGUI extends JFrame {
    private LibraryDataService dataService;
    private JTabbedPane tabbedPane;
    private Admin currentAdmin;

    // 图书管理组件
    private JTable bookTable;
    private DefaultTableModel bookTableModel;
    private JTextField searchBookField;

    // 读者管理组件
    private JTable readerTable;
    private DefaultTableModel readerTableModel;
    private JTextField searchReaderField;

    // 修改构造函数，接收管理员参数
    public LibraryManagementGUI(Admin admin) {
        this.currentAdmin = admin;
        this.dataService = new LibraryDataService();
        initializeUI();
        showWelcomeMessage();
    }

    // 保持原有构造函数以兼容性
    public LibraryManagementGUI() {
        this(null);
    }

    private void initializeUI() {
        setTitle("图书借阅管理系统 - 管理员：" + (currentAdmin != null ? currentAdmin.getRealName() : "系统"));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1200, 800);
        setLocationRelativeTo(null);

        // 创建选项卡
        tabbedPane = new JTabbedPane();

        // 图书管理面板
        tabbedPane.addTab("图书管理", createBookManagementPanel());

        // 读者管理面板
        tabbedPane.addTab("读者管理", createReaderManagementPanel());

        // 规则管理面板
        tabbedPane.addTab("借阅规则", createRuleManagementPanel());

        // 数据统计面板
        tabbedPane.addTab("数据统计", createStatisticsPanel());

        add(tabbedPane);

        // 添加状态栏
        add(createStatusBar(), BorderLayout.SOUTH);
    }

    private void showWelcomeMessage() {
        if (currentAdmin != null) {
            System.out.println("欢迎管理员 " + currentAdmin.getRealName() + " 登录系统");
        }
    }

    private JPanel createStatusBar() {
        JPanel statusPanel = new JPanel(new BorderLayout());
        statusPanel.setBorder(BorderFactory.createEtchedBorder());

        JLabel statusLabel = new JLabel("就绪");
        statusPanel.add(statusLabel, BorderLayout.WEST);

        if (currentAdmin != null) {
            JLabel userLabel = new JLabel("当前用户: " + currentAdmin.getRealName());
            statusPanel.add(userLabel, BorderLayout.EAST);
        }

        return statusPanel;
    }

    private JPanel createBookManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 搜索栏
        JPanel searchPanel = new JPanel(new FlowLayout());
        searchPanel.add(new JLabel("搜索:"));
        searchBookField = new JTextField(20);
        searchPanel.add(searchBookField);

        JButton searchButton = new JButton("搜索");
        searchButton.addActionListener(e -> searchBooks());
        searchPanel.add(searchButton);

        JButton addButton = new JButton("添加图书");
        addButton.addActionListener(e -> showAddBookDialog());
        searchPanel.add(addButton);

        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> refreshBookTable());
        searchPanel.add(refreshButton);

        panel.add(searchPanel, BorderLayout.NORTH);

        // 图书表格
        String[] columns = {"ISBN", "书名", "作者", "出版社", "出版日期", "价格", "分类", "位置", "总复本", "可借复本", "状态"};
        bookTableModel = new DefaultTableModel(columns, 0) {
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                // 设置价格列为Double类型以便正确排序
                if (columnIndex == 5) return Double.class;
                return Object.class;
            }
        };
        bookTable = new JTable(bookTableModel);
        bookTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        bookTable.setAutoCreateRowSorter(true); // 启用排序

        JScrollPane scrollPane = new JScrollPane(bookTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 操作按钮
        JPanel buttonPanel = new JPanel();
        JButton editButton = new JButton("编辑选中");
        editButton.addActionListener(e -> editSelectedBook());
        buttonPanel.add(editButton);

        JButton deleteButton = new JButton("删除选中");
        deleteButton.addActionListener(e -> deleteSelectedBook());
        buttonPanel.add(deleteButton);

        JButton viewDetailsButton = new JButton("查看详情");
        viewDetailsButton.addActionListener(e -> viewBookDetails());
        buttonPanel.add(viewDetailsButton);

        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 初始加载数据
        refreshBookTable();

        return panel;
    }

    private JPanel createReaderManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 搜索栏
        JPanel searchPanel = new JPanel(new FlowLayout());
        searchPanel.add(new JLabel("搜索:"));
        searchReaderField = new JTextField(20);
        searchPanel.add(searchReaderField);

        JButton searchButton = new JButton("搜索");
        searchButton.addActionListener(e -> searchReaders());
        searchPanel.add(searchButton);

        JButton addButton = new JButton("添加读者");
        addButton.addActionListener(e -> showAddReaderDialog());
        searchPanel.add(addButton);

        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> refreshReaderTable());
        searchPanel.add(refreshButton);

        panel.add(searchPanel, BorderLayout.NORTH);

        // 读者表格
        String[] columns = {"读者ID", "姓名", "性别", "电话", "邮箱", "部门", "类型", "状态", "注册日期", "有效期至"};
        readerTableModel = new DefaultTableModel(columns, 0);
        readerTable = new JTable(readerTableModel);
        readerTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        readerTable.setAutoCreateRowSorter(true);

        JScrollPane scrollPane = new JScrollPane(readerTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 操作按钮
        JPanel buttonPanel = new JPanel();
        JButton editButton = new JButton("编辑选中");
        editButton.addActionListener(e -> editSelectedReader());
        buttonPanel.add(editButton);

        JButton deleteButton = new JButton("删除选中");
        deleteButton.addActionListener(e -> deleteSelectedReader());
        buttonPanel.add(deleteButton);

        JButton viewDetailsButton = new JButton("查看详情");
        viewDetailsButton.addActionListener(e -> viewReaderDetails());
        buttonPanel.add(viewDetailsButton);

        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 初始加载数据
        refreshReaderTable();

        return panel;
    }

    private JPanel createRuleManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        String[] columns = {"读者类型", "最大借书数", "借书天数", "最大续借次数", "可预约", "最大预约数", "超期罚款率"};
        DefaultTableModel ruleModel = new DefaultTableModel(columns, 0);
        JTable ruleTable = new JTable(ruleModel);

        // 加载规则数据
        for (BorrowRule rule : dataService.getAllBorrowRules().values()) {
            ruleModel.addRow(new Object[]{
                    getReaderTypeText(rule.getReaderType()),
                    rule.getMaxBorrowCount(),
                    rule.getMaxBorrowDays(),
                    rule.getMaxRenewTimes(),
                    rule.canReserve() ? "是" : "否",
                    rule.getMaxReserveCount(),
                    rule.getOverdueFineRate() + "元/天"
            });
        }

        JScrollPane scrollPane = new JScrollPane(ruleTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        JButton editButton = new JButton("编辑规则");
        editButton.addActionListener(e -> showEditRuleDialog());
        panel.add(editButton, BorderLayout.SOUTH);

        return panel;
    }

    private JPanel createStatisticsPanel() {
        JPanel panel = new JPanel(new GridLayout(2, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 获取统计数据
        int totalBooks = dataService.getTotalBookCount();
        int totalReaders = dataService.getTotalReaderCount();
        java.util.Map<String, Integer> categoryStats = dataService.getBooksByCategory();

        // 统计卡片
        JPanel bookStats = createStatCard("📚 图书统计",
                "总图书数: " + totalBooks + " 本",
                "分类数量: " + categoryStats.size() + " 类");

        JPanel readerStats = createStatCard("👥 读者统计",
                "总读者数: " + totalReaders + " 位",
                "活跃读者: " + getActiveReadersCount() + " 位");

        JPanel categoryStatsPanel = createStatCard("📊 分类统计",
                getTopCategories(categoryStats), "");

        JPanel systemStats = createStatCard("⚙️ 系统信息",
                "借阅规则: " + dataService.getAllBorrowRules().size() + " 种",
                "最后更新: " + java.time.LocalDateTime.now().format(
                        java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));

        panel.add(bookStats);
        panel.add(readerStats);
        panel.add(categoryStatsPanel);
        panel.add(systemStats);

        return panel;
    }

    private JPanel createStatCard(String title, String info1, String info2) {
        JPanel card = new JPanel(new BorderLayout());
        card.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.GRAY),
                BorderFactory.createEmptyBorder(10, 10, 10, 10)
        ));
        card.setBackground(Color.WHITE);

        JLabel titleLabel = new JLabel(title, JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        card.add(titleLabel, BorderLayout.NORTH);

        JPanel infoPanel = new JPanel(new GridLayout(2, 1));
        infoPanel.add(new JLabel(info1));
        if (!info2.isEmpty()) {
            infoPanel.add(new JLabel(info2));
        }
        card.add(infoPanel, BorderLayout.CENTER);

        return card;
    }

    // 图书管理相关方法
    private void refreshBookTable() {
        bookTableModel.setRowCount(0);

        // 从数据库获取所有图书
        java.util.List<Book> books = dataService.getAllBooks();

        for (Book book : books) {
            bookTableModel.addRow(new Object[]{
                    book.getIsbn(),
                    book.getTitle(),
                    book.getAuthor(),
                    book.getPublisher(),
                    book.getPublishDate(),
                    book.getPrice(),
                    book.getCategory(),
                    book.getLocation(),
                    book.getTotalCopies(),
                    book.getAvailableCopies(),
                    getBookStatusText(book.getStatus())
            });
        }

        // 显示统计信息
        showBookStatistics();
    }

    private void searchBooks() {
        String keyword = searchBookField.getText().trim();
        if (!keyword.isEmpty()) {
            bookTableModel.setRowCount(0);

            // 从数据库搜索图书
            java.util.List<Book> books = dataService.searchBooks(keyword);

            for (Book book : books) {
                bookTableModel.addRow(new Object[]{
                        book.getIsbn(),
                        book.getTitle(),
                        book.getAuthor(),
                        book.getPublisher(),
                        book.getPublishDate(),
                        book.getPrice(),
                        book.getCategory(),
                        book.getLocation(),
                        book.getTotalCopies(),
                        book.getAvailableCopies(),
                        getBookStatusText(book.getStatus())
                });
            }

            JOptionPane.showMessageDialog(this,
                    "找到 " + books.size() + " 本相关图书",
                    "搜索结果", JOptionPane.INFORMATION_MESSAGE);
        } else {
            refreshBookTable();
        }
    }

    private void showAddBookDialog() {
        JDialog dialog = new JDialog(this, "添加新图书", true);
        dialog.setSize(500, 400);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        JPanel formPanel = new JPanel(new GridLayout(8, 2, 10, 10));
        formPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JTextField isbnField = new JTextField();
        JTextField titleField = new JTextField();
        JTextField authorField = new JTextField();
        JTextField publisherField = new JTextField();
        JTextField publishDateField = new JTextField();
        JTextField priceField = new JTextField();
        JTextField categoryField = new JTextField();
        JTextField locationField = new JTextField();
        JTextField copiesField = new JTextField("1");

        formPanel.add(new JLabel("ISBN*:"));
        formPanel.add(isbnField);
        formPanel.add(new JLabel("书名*:"));
        formPanel.add(titleField);
        formPanel.add(new JLabel("作者*:"));
        formPanel.add(authorField);
        formPanel.add(new JLabel("出版社:"));
        formPanel.add(publisherField);
        formPanel.add(new JLabel("出版日期 (YYYY-MM-DD):"));
        formPanel.add(publishDateField);
        formPanel.add(new JLabel("价格:"));
        formPanel.add(priceField);
        formPanel.add(new JLabel("分类:"));
        formPanel.add(categoryField);
        formPanel.add(new JLabel("位置:"));
        formPanel.add(locationField);
        formPanel.add(new JLabel("复本数:"));
        formPanel.add(copiesField);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");

        saveButton.addActionListener(e -> {
            // 验证并保存图书
            if (saveBookFromDialog(isbnField, titleField, authorField, publisherField,
                    publishDateField, priceField, categoryField, locationField, copiesField)) {
                dialog.dispose();
                refreshBookTable();
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        dialog.add(formPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    private boolean saveBookFromDialog(JTextField isbnField, JTextField titleField, JTextField authorField,
                                       JTextField publisherField, JTextField publishDateField, JTextField priceField,
                                       JTextField categoryField, JTextField locationField, JTextField copiesField) {
        try {
            String isbn = isbnField.getText().trim();
            String title = titleField.getText().trim();
            String author = authorField.getText().trim();

            if (isbn.isEmpty() || title.isEmpty() || author.isEmpty()) {
                JOptionPane.showMessageDialog(this, "ISBN、书名和作者为必填项!", "输入错误", JOptionPane.WARNING_MESSAGE);
                return false;
            }

            // 检查ISBN是否已存在
            if (dataService.findBookByIsbn(isbn) != null) {
                JOptionPane.showMessageDialog(this, "ISBN已存在!", "错误", JOptionPane.ERROR_MESSAGE);
                return false;
            }

            // 解析其他字段
            String publisher = publisherField.getText().trim();
            java.time.LocalDate publishDate = null;
            if (!publishDateField.getText().trim().isEmpty()) {
                publishDate = java.time.LocalDate.parse(publishDateField.getText().trim());
            } else {
                publishDate = java.time.LocalDate.now();
            }

            double price = 0.0;
            if (!priceField.getText().trim().isEmpty()) {
                price = Double.parseDouble(priceField.getText().trim());
            }

            String category = categoryField.getText().trim();
            if (category.isEmpty()) category = "未分类";

            String location = locationField.getText().trim();
            if (location.isEmpty()) location = "流通书库";

            int copies = 1;
            if (!copiesField.getText().trim().isEmpty()) {
                copies = Integer.parseInt(copiesField.getText().trim());
            }

            // 创建图书对象
            Book newBook = new Book(isbn, title, author, publisher, publishDate, price, category, location, copies);

            // 保存到数据库
            if (dataService.addBook(newBook)) {
                JOptionPane.showMessageDialog(this, "图书添加成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
                return true;
            } else {
                JOptionPane.showMessageDialog(this, "添加失败!", "错误", JOptionPane.ERROR_MESSAGE);
                return false;
            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "输入格式错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }

    private void editSelectedBook() {
        int selectedRow = bookTable.getSelectedRow();
        if (selectedRow >= 0) {
            String isbn = (String) bookTableModel.getValueAt(selectedRow, 0);
            Book book = dataService.findBookByIsbn(isbn);
            if (book != null) {
                showEditBookDialog(book);
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择一本图书!");
        }
    }

    private void showEditBookDialog(Book book) {
        // 实现编辑图书对话框（类似添加对话框，但预填充数据）
        JOptionPane.showMessageDialog(this, "编辑功能开发中...", "提示", JOptionPane.INFORMATION_MESSAGE);
    }

    private void deleteSelectedBook() {
        int selectedRow = bookTable.getSelectedRow();
        if (selectedRow >= 0) {
            String isbn = (String) bookTableModel.getValueAt(selectedRow, 0);
            String title = (String) bookTableModel.getValueAt(selectedRow, 1);

            int confirm = JOptionPane.showConfirmDialog(this,
                    "确定要删除图书《" + title + "》吗?", "确认删除", JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                if (dataService.deleteBook(isbn)) {
                    JOptionPane.showMessageDialog(this, "删除成功!");
                    refreshBookTable();
                } else {
                    JOptionPane.showMessageDialog(this, "删除失败!");
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择一本图书!");
        }
    }

    private void viewBookDetails() {
        int selectedRow = bookTable.getSelectedRow();
        if (selectedRow >= 0) {
            String isbn = (String) bookTableModel.getValueAt(selectedRow, 0);
            Book book = dataService.findBookByIsbn(isbn);
            if (book != null) {
                showBookDetailsDialog(book);
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择一本图书!");
        }
    }

    private void showBookDetailsDialog(Book book) {
        JDialog dialog = new JDialog(this, "图书详情", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(9, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        panel.add(new JLabel("ISBN:"));
        panel.add(new JLabel(book.getIsbn()));
        panel.add(new JLabel("书名:"));
        panel.add(new JLabel(book.getTitle()));
        panel.add(new JLabel("作者:"));
        panel.add(new JLabel(book.getAuthor()));
        panel.add(new JLabel("出版社:"));
        panel.add(new JLabel(book.getPublisher()));
        panel.add(new JLabel("出版日期:"));
        panel.add(new JLabel(book.getPublishDate().toString()));
        panel.add(new JLabel("价格:"));
        panel.add(new JLabel(String.format("¥%.2f", book.getPrice())));
        panel.add(new JLabel("分类:"));
        panel.add(new JLabel(book.getCategory()));
        panel.add(new JLabel("位置:"));
        panel.add(new JLabel(book.getLocation()));
        panel.add(new JLabel("状态:"));
        panel.add(new JLabel(getBookStatusText(book.getStatus())));

        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> dialog.dispose());

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(closeButton, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    // 读者管理相关方法
    private void refreshReaderTable() {
        readerTableModel.setRowCount(0);

        // 从数据库获取所有读者
        java.util.List<Reader> readers = dataService.getAllReaders();

        for (Reader reader : readers) {
            readerTableModel.addRow(new Object[]{
                    reader.getReaderId(),
                    reader.getName(),
                    reader.getGender(),
                    reader.getPhone(),
                    reader.getEmail(),
                    reader.getDepartment(),
                    getReaderTypeText(reader.getType()),
                    getReaderStatusText(reader.getStatus()),
                    reader.getRegisterDate(),
                    reader.getExpiryDate()
            });
        }
    }

    private void searchReaders() {
        String keyword = searchReaderField.getText().trim();
        if (!keyword.isEmpty()) {
            readerTableModel.setRowCount(0);

            // 从数据库搜索读者
            java.util.List<Reader> readers = dataService.searchReaders(keyword);

            for (Reader reader : readers) {
                readerTableModel.addRow(new Object[]{
                        reader.getReaderId(),
                        reader.getName(),
                        reader.getGender(),
                        reader.getPhone(),
                        reader.getEmail(),
                        reader.getDepartment(),
                        getReaderTypeText(reader.getType()),
                        getReaderStatusText(reader.getStatus()),
                        reader.getRegisterDate(),
                        reader.getExpiryDate()
                });
            }

            JOptionPane.showMessageDialog(this,
                    "找到 " + readers.size() + " 位相关读者",
                    "搜索结果", JOptionPane.INFORMATION_MESSAGE);
        } else {
            refreshReaderTable();
        }
    }

    private void showAddReaderDialog() {
        // 实现添加读者对话框
        JOptionPane.showMessageDialog(this, "添加读者功能开发中...", "提示", JOptionPane.INFORMATION_MESSAGE);
    }

    private void editSelectedReader() {
        int selectedRow = readerTable.getSelectedRow();
        if (selectedRow >= 0) {
            JOptionPane.showMessageDialog(this, "编辑读者功能开发中...", "提示", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, "请先选择一位读者!");
        }
    }

    private void deleteSelectedReader() {
        int selectedRow = readerTable.getSelectedRow();
        if (selectedRow >= 0) {
            String readerId = (String) readerTableModel.getValueAt(selectedRow, 0);
            String name = (String) readerTableModel.getValueAt(selectedRow, 1);

            int confirm = JOptionPane.showConfirmDialog(this,
                    "确定要删除读者 " + name + " 吗?", "确认删除", JOptionPane.YES_NO_OPTION);

            if (confirm == JOptionPane.YES_OPTION) {
                if (dataService.deleteReader(readerId)) {
                    JOptionPane.showMessageDialog(this, "删除成功!");
                    refreshReaderTable();
                } else {
                    JOptionPane.showMessageDialog(this, "删除失败!");
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择一位读者!");
        }
    }

    private void viewReaderDetails() {
        int selectedRow = readerTable.getSelectedRow();
        if (selectedRow >= 0) {
            String readerId = (String) readerTableModel.getValueAt(selectedRow, 0);
            Reader reader = dataService.findReaderById(readerId);
            if (reader != null) {
                showReaderDetailsDialog(reader);
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择一位读者!");
        }
    }

    private void showReaderDetailsDialog(Reader reader) {
        JDialog dialog = new JDialog(this, "读者详情", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new GridLayout(10, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        panel.add(new JLabel("读者ID:"));
        panel.add(new JLabel(reader.getReaderId()));
        panel.add(new JLabel("姓名:"));
        panel.add(new JLabel(reader.getName()));
        panel.add(new JLabel("性别:"));
        panel.add(new JLabel(reader.getGender()));
        panel.add(new JLabel("电话:"));
        panel.add(new JLabel(reader.getPhone()));
        panel.add(new JLabel("邮箱:"));
        panel.add(new JLabel(reader.getEmail()));
        panel.add(new JLabel("部门:"));
        panel.add(new JLabel(reader.getDepartment()));
        panel.add(new JLabel("类型:"));
        panel.add(new JLabel(getReaderTypeText(reader.getType())));
        panel.add(new JLabel("状态:"));
        panel.add(new JLabel(getReaderStatusText(reader.getStatus())));
        panel.add(new JLabel("注册日期:"));
        panel.add(new JLabel(reader.getRegisterDate().toString()));
        panel.add(new JLabel("有效期至:"));
        panel.add(new JLabel(reader.getExpiryDate().toString()));

        JButton closeButton = new JButton("关闭");
        closeButton.addActionListener(e -> dialog.dispose());

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(closeButton, BorderLayout.SOUTH);
        dialog.setVisible(true);
    }

    private void showEditRuleDialog() {
        JOptionPane.showMessageDialog(this, "编辑借阅规则功能开发中...", "提示", JOptionPane.INFORMATION_MESSAGE);
    }

    // 工具方法
    private String getBookStatusText(Book.BookStatus status) {
        switch (status) {
            case AVAILABLE: return "可借";
            case BORROWED: return "已借出";
            case RESERVED: return "已预约";
            case UNDER_REPAIR: return "维修中";
            case LOST: return "已遗失";
            default: return "未知";
        }
    }

    private String getReaderTypeText(Reader.ReaderType type) {
        switch (type) {
            case STUDENT: return "学生";
            case TEACHER: return "教师";
            case STAFF: return "职工";
            case EXTERNAL: return "校外读者";
            default: return "未知";
        }
    }

    private String getReaderStatusText(Reader.ReaderStatus status) {
        switch (status) {
            case ACTIVE: return "正常";
            case INACTIVE: return "停用";
            case FROZEN: return "冻结";
            case LOST_CARD: return "挂失";
            default: return "未知";
        }
    }

    private void showBookStatistics() {
        int totalBooks = dataService.getTotalBookCount();
        java.util.Map<String, Integer> categoryStats = dataService.getBooksByCategory();

        System.out.println("📊 图书统计:");
        System.out.println("总图书数: " + totalBooks);
        System.out.println("分类数量: " + categoryStats.size());

        for (java.util.Map.Entry<String, Integer> entry : categoryStats.entrySet()) {
            System.out.println("  " + entry.getKey() + ": " + entry.getValue() + " 本");
        }
    }

    private int getActiveReadersCount() {
        // 简化实现，实际应该从数据库查询
        java.util.List<Reader> readers = dataService.getAllReaders();
        int count = 0;
        for (Reader reader : readers) {
            if (reader.getStatus() == Reader.ReaderStatus.ACTIVE) {
                count++;
            }
        }
        return count;
    }

    private String getTopCategories(java.util.Map<String, Integer> categoryStats) {
        if (categoryStats.isEmpty()) {
            return "暂无分类数据";
        }

        // 取前3个分类
        java.util.List<java.util.Map.Entry<String, Integer>> sorted = new java.util.ArrayList<>(categoryStats.entrySet());
        sorted.sort(java.util.Map.Entry.comparingByValue(java.util.Collections.reverseOrder()));

        StringBuilder result = new StringBuilder();
        int count = 0;
        for (java.util.Map.Entry<String, Integer> entry : sorted) {
            if (count >= 3) break;
            if (count > 0) result.append(", ");
            result.append(entry.getKey()).append(": ").append(entry.getValue());
            count++;
        }

        return result.toString();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                // 修复：使用 getSystemLookAndFeelClassName() 而不是 getSystemLookAndFeel()
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                System.err.println("设置系统外观失败: " + e.getMessage());
                // 如果设置系统外观失败，使用默认外观
                try {
                    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            // 启动登录界面而不是直接启动管理员界面
            LoginFrame loginFrame = new LoginFrame();
            loginFrame.setVisible(true);
        });
    }
}